package models

import (
	"fmt"
	"git.inedcn.com/ined/cmn"
	"log"
	"rongyy/src/app"
	"rongyy/src/middlewares"
)

type CardModel struct {
	Id         int64        `xorm:"pk autoincr" json:"id"`
	Age        string       `json:"age"`                       // 生成的订单号
	CardNo     string       `json:"card_no"`                   // 状态 0启用 1停用
	EcardNo    string       `json:"ecard_no"`                  // 备注
	Empi       string       `json:"empi"`                      // 创建人
	IdNo       string       `json:"id_no"`                     // 创建时间
	Mobile     string       `json:"mobile"`                    // 创建人
	Nation     string       `json:"nations"`                   // 创建人
	RealName   string       `json:"real_name"`                 // 创建人
	Sex        int          `json:"sex"`                       // 创建人
	SourceId   string       `json:"source_id"`                 // 创建人
	Occupation string       `json:"occupation"`                // 创建人
	CreatedAt  cmn.JsonTime `xorm:"created" json:"created_at"` // 创建时间
	UpdatedAt  cmn.JsonTime `xorm:"updated" json:"updated_at"` // 更新时间
	Hospital   string       `json:"hospital" xorm:"-"`
	Unionid    string       `json:"unionid" xorm:"-"`
	DOB        string       `json:"dob" xorm:"-"`
}

type EcardCreateReq struct {
	Age           string `json:"age"`
	Unionid       string `json:"unionid"`
	Wxid          int    `json:"wxid"`
	PatientName   string `json:"patient_name"`
	IdNo          string `json:"id_no"`
	Sex           string `json:"sex"`
	Dob           string `json:"dob"`
	Mobile        string `json:"mobile"`
	Job           string `json:"job"`
	MaritalStatus string `json:"marital_status"`
	Address       string `json:"address"`
	HospitalCode  string `json:"hospitalCode"`
	ContactName   string `json:"contact_name"`
	ContactTelNo  string `json:"contact_tel_no"`
	ContactIDNo   string `json:"contact_id_no"`
	IdType        string `json:"id_type"`
	Nation        string `json:"nation"`
	EcardNo       string `json:"ecard_no"`
}
type CardBindModel struct {
	Id        int64        `json:"id"`
	Mobile    string       `json:"mobile"`
	Openid    string       `json:"openid"`                    //
	Unionid   string       `json:"unionid"`                   //
	OrgId     string       `json:"org_id"`                    // 没用
	PatientId int64        `json:"patient_id"`                //
	Status    int8         `json:"status"`                    // 状态 0启用 1停用
	CreatedAt cmn.JsonTime `xorm:"created" json:"created_at"` // 创建时间
	UpdatedAt cmn.JsonTime `xorm:"updated" json:"updated_at"` // 更新时间
	Hospital  string       `json:"hospital" xorm:"-"`
}

//	type CardReqParams struct {
//		PatientName string `json: "patient_name"`
//		IDNo        string `json: "id_no"`
//	}
type CardReqParams struct {
	PatientId   string `json:"patient_id"`
	PatientName string `json:"patient_name"`
	CardType    string `json:"card_type"`
	IDCardType  string `json:"id_card_type"`
	IDNo        string `json:"id_no"`
	Phone       string `json:"phone"`
	TelephoneNo string `json:"telephone_no"`
}

type ReqCardQuery struct {
	Limit     int    `json:"limit"`
	Offset    int    `json:"offset"`
	PatientId string `json:"patient_id"`
	OrderSn   string `json:"order_sn"`
	Status    string `json:"status"`
}

type GetAge struct {
	PatientId string `json:"patient_id"`
}

func (this *CardModel) GetAge(patientId string) (*CardModel, error) {
	cd := &CardModel{}
	_, err := app.DB().Table("ho_patientcard").Where("source_id = ?", patientId).Get(cd)
	if err != nil {
		return nil, err
	}
	return cd, nil
}

func (this *CardModel) String() string {
	return fmt.Sprintf("userid:")
}

func (card *CardModel) TableName() string {
	return "ho_patientcard"
}

func (card *CardModel) Insert(ecard *CardModel) (*CardModel, error) {
	_, err := app.DB().Insert(ecard)
	if err != nil {
		return nil, err
	}
	_, err = app.DB().Where("ecard_no = ?", ecard.EcardNo).Get(card)
	return card, nil
}
func (cm *CardModel) FindById(id int64) (*CardModel, bool, error) {
	card := new(CardModel)
	has, err := app.DB().ID(id).Get(card)
	if err != nil {
		return nil, has, err
	}
	return card, has, nil
}

func (cm *CardModel) FindByECard(card_no string, hospital string) (*CardModel, bool, error) {
	card := new(CardModel)
	has, err := app.DB().Where("ecard_no = ?", card_no).Get(card)
	if err != nil {
		return nil, has, err
	}
	return card, has, nil
}

func (card *CardModel) BindCard(cardbind *CardBindModel) error {
	middlewares.Logger.Println("绑卡入参", cardbind)
	_, err := app.DB().Table("ho_patientcard_item").Insert(cardbind)
	if err != nil {
		log.Println(err)
		return err
	}
	return nil
}

func (card *CardModel) Batch() error {
	binds := make([]CardBindModel, 0)
	err := app.DB().Table("ho_patientcard_item").Limit(15000, 1).Find(&binds)
	if err != nil {
		log.Println(err)
		return err
	}
	var i int
	fmt.Println(len(binds))
	for i = 0; i < len(binds); i++ {
		user := &UserModel{}
		_, err := app.DB().Table("wx_userinfo").Where("openid = ?", binds[i].Openid).Get(user)
		if err != nil {
			fmt.Println(err)
			return err
		}
		newCardBindModel := new(CardBindModel)
		newCardBindModel.Unionid = user.Unionid
		_, err = app.DB().Table("ho_patientcard_item").Where("openid = ?", binds[i].Openid).Cols("unionid").Update(newCardBindModel)
		fmt.Println(err)
	}
	return nil
}

func (card *CardModel) BindPatientIdToCardM(sourceId string, ecardNo string, hospital string) error {
	c := &CardModel{}
	c.SourceId = sourceId
	_, err := app.DB().Table("ho_patientcard").Where("ecard_no = ?", ecardNo).Cols("source_id").Update(c)
	if err != nil {
		return err
	}
	return err
}

func (card *CardModel) UpdateEcardNoM(ecardNo string, idNo string, empi string, hospital string) error {
	c := &CardModel{}
	c.EcardNo = ecardNo
	c.Empi = empi
	_, err := app.DB().Table("ho_patientcard").Where("id_no = ?", idNo).Cols("ecard_no", "empi").Update(c)
	if err != nil {
		return err
	}
	return err
}

func (card *CardModel) UpdateEcardByPid(ecardNo string, pid string) error {
	c := &CardModel{}
	c.EcardNo = ecardNo
	_, err := app.DB().Table("ho_patientcard").Where("source_id = ?", pid).Cols("ecard_no").Update(c)
	if err != nil {
		return err
	}
	return err
}
func (card *CardModel) FindCardByIDM(idNo string) (*CardModel, bool, error) {
	c := &CardModel{}
	has, err := app.DB().Table("ho_patientcard").Where("id_no = ?", idNo).Get(c)
	if err != nil {
		return nil, false, err
	}
	return c, has, nil
}

func (card *CardModel) FindMedcardByIDM(idNo string) (*CardModel, bool, error) {
	c := &CardModel{}
	has, err := app.DB().Table("ho_patientcard").Where("id_no = ?", idNo).Get(c)
	if err != nil {
		return nil, false, err
	}
	return c, has, nil
}

func (cm *CardModel) FindCardByCardNoM(ecard_no string) (*CardModel, bool, error) {
	card := &CardModel{}
	has, err := app.DB().Table("ho_patientcard").Where("ecard_no = ?", ecard_no).Get(card)
	if err != nil {
		return nil, false, err
	}
	return card, has, nil
}

func (cm *CardModel) FindMedCardByCardNoM(card_no string) (*CardModel, bool, error) {
	card := &CardModel{}
	has, err := app.DB().Table("ho_patientcard_item").Alias("hpi").
		Join("RIGHT", "ho_patientcard AS hp", "hpi.patient_id = hp.source_id").
		Select("hp.source_id, hp.card_no, hp.ecard_no, hp.real_name,  hp.sex, hp.age, hp.mobile, hp.id_no, hp.occupation, hp.empi, hpi.unionid").
		Where("hp.card_no = ? and status = 1", card_no).Get(card)
	fmt.Println(err)
	if err != nil {
		return nil, has, err
	}
	return card, has, nil
}

func (cm *CardModel) UnbindCard(unionid string, id int64) error {
	cardBind := &CardBindModel{}
	cardBind.Status = 0
	_, err := app.DB().Table("ho_patientcard_item").Where("unionid = ? and patient_id = ?", unionid, id).Cols("status").Update(cardBind)
	if err != nil {
		return err
	}
	return err
}

func (card *CardModel) BatchGetItems() ([]CardBindModel, error) {
	binds := make([]CardBindModel, 0)
	err := app.DB().Table("ho_patientcard_item").Distinct("openid").Cols("openid").Find(&binds)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	return binds, nil
}

func (card *CardModel) InsertCardBindModel(ecard *CardBindModel) error {
	_, err := app.DB().Insert(ecard)
	if err != nil {
		log.Println(err)
		return err
	}
	return nil
}

type CardDecrptModel struct {
	Id       int64  `json:"id"`
	IdNo     string `json:"id_no"`     // 创建时间
	RealName string `json:"real_name"` // 创建人tal" xorm:"-"`
	Mobile   string `json:"mobile"`    // 创建人tal" xorm:"-"`
}

type CardDecrptRespModel struct {
	Data   []CardDecrptModel `json:"data"` // 创建时间
	Result string            `json:"result"`
	Return string            `json:"return"`
}

func (card *CardModel) GetAllCards(hospital string) ([]CardDecrptModel, error) {
	cards := make([]CardDecrptModel, 0)
	err := app.DB().Table("ho_patientcard").Where("LENGTH(mobile) != 11").Find(&cards)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	return cards, nil
}

func (card *CardModel) GetAllCardItems(hospital string, limit int, offset int) ([]CardBindModel, error) {
	cards := make([]CardBindModel, 0)
	err := app.DB().Table("ho_patientcard_item").Where("ISNULL(unionid)").Limit(limit, offset).Find(&cards)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	return cards, nil
}

func (cm *CardModel) UpdateDecryptData(hospital string, id int64, idNo string, mobile string, realName string) error {
	card := &CardModel{}
	card.IdNo = idNo
	card.Mobile = mobile
	card.RealName = realName
	_, err := app.DB().Table("ho_patientcard").Where("id = ?", id).Cols("real_name", "mobile", "id_no").Update(card)
	if err != nil {
		log.Println(err)
		return err
	}
	return nil
}

type u struct {
	Openid  string `json:"openid"`  //
	Unionid string `json:"unionid"` //
}

func (card *CardModel) GetUserUnionid(openid string) (string, error) {
	user := &u{}
	has, err := app.DB().Table("wx_user").Where("openid = ?", openid).Get(user)
	if !has {
		return "nodata", err
	}
	if err != nil {
		log.Println(err)
		return "nodata", err
	}
	return user.Unionid, nil
}

func (card *CardModel) UpdateCardItemUnionid(openid string, unionid string) error {
	user := &u{}
	user.Unionid = unionid
	_, err := app.DB().Table("ho_patientcard_item").Where("openid = ?", openid).Cols("unionid", "updated_at").Update(user)
	if err != nil {
		log.Println(err)
		return err
	}
	return nil
}

func (card *CardModel) FindAllWithoutPatientId() ([]CardModel, error) {
	cards := make([]CardModel, 0)
	err := app.DB().Table("ho_patientcard").Where("source_id is NULL").Find(&cards)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	return cards, nil
}

//
//type PatInfo struct {
//  XMLName     xml.Name `xml:"PatInfo" json:"-"`
//  PatientID   string   `xml:"PatientID" json:"patient_id"`
//  PatientName string   `xml:"PatientName" json:"patient_name"`
//  Sex         string   `xml:"Sex" json:"sex"`
//  SexCode     string   `xml:"SexCode" json:"sex_code"`
//  DOB         string   `xml:"DOB" json:"dob"`
//  TelephoneNo string   `xml:"TelephoneNo" json:"telephone_no"`
//  Mobile      string   `xml:"Mobile" json:"mobile"`
//  Address     string   `xml:"Address" json:"address"`
//  IDTypeCode  string   `xml:"IDTypeCode" json:"id_type_code"`
//  IDNo        string   `xml:"IDNo" json:"id_no"`
//  AccInfo     string   `xml:"AccInfo" json:"acc_info"`
//  PatientCard string   `xml:"PatientCard" json:"patient_card"`
//  YBFlag      string   `xml:"YBFlag" json:"yb_flag"`
//  PatType     string   `xml:"PatType" json:"pat_type"`
//  PatTypeCode string   `xml:"PatTypeCode" json:"pat_type_code"`
//}
//
//type Resp3300 struct {
//  XMLName       xml.Name  `xml:"Response" json:"-"`
//  ResultCode    string    `xml:"ResultCode" json:"result_code"` // 交易结果 0：成功； 非0：错误
//  ResultContent string    `xml:"ResultContent" json:"result_content"`
//  PatInfos      []PatInfo `xml:"PatInfos>PatInfo" json:"pat_infos"`
//}

type Boshuai struct {
	IsSuccess bool     `json:"is_success"`
	Data      Resp3300 `json:"data"`
	Msg       string   `json:"msg"`
}

func (card *CardModel) UpdateSourceId(idNo string, patientId string) error {
	cd := &CardModel{}
	cd.SourceId = patientId
	_, err := app.DB().Table("ho_patientcard").Where("id_no = ?", idNo).Cols("source_id").Update(cd)
	if err != nil {
		log.Println(err)
		return err
	}
	return nil
}

func (card *CardModel) FindByPatientId(patientId string) (*CardModel, bool, error) {
	cd := &CardModel{}
	cd.SourceId = patientId
	has, err := app.DB().Table("ho_patientcard").Where("source_id = ?", patientId).Get(cd)
	if err != nil {
		return nil, false, err
	}
	return cd, has, nil
}

func (card *CardModel) UpdatePatientInfo(idNo string, realName string, sourceId string) error {
	cd := &CardModel{}
	cd.RealName = realName
	cd.SourceId = sourceId
	_, err := app.DB().Table("ho_patientcard").Where("id_no = ?", idNo).Cols("real_name", "source_id").Update(cd)
	if err != nil {
		log.Println(err)
		return err
	}
	return nil
}

func (card *CardModel) UpdateNameTel(patientId string, mobile string, name string) error {
	cd := &CardModel{}
	cd.SourceId = patientId
	cd.Mobile = mobile
	cd.RealName = name
	_, err := app.DB().Table("ho_patientcard").Where("source_id = ?", patientId).Cols("mobile", "real_name").Update(cd)
	if err != nil {
		log.Println(err)
		return err
	}
	return nil
}

func (card *CardModel) GetPatientByIdNo(idNo string) (*CardModel, error) {
	cd := &CardModel{}
	_, err := app.DB().Table("ho_patientcard").Where("id_no = ?", idNo).Get(cd)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	return cd, nil
}

func (card *CardModel) GetPatientBySourceId(sid string) (*CardModel, bool, error) {
	cd := &CardModel{}
	has, err := app.DB().Table("ho_patientcard").Where("source_id = ?", sid).Get(cd)
	if err != nil {
		return nil, false, err
	}
	return cd, has, nil
}

func (card *CardModel) FindBindCardInfo(id int64, unionid string) (*CardBindModel, bool, error) {
	cd := &CardBindModel{}
	has, err := app.DB().Table("ho_patientcard_item").Where("patient_id = ? and unionid = ? and status = 1", id, unionid).Get(cd)
	if err != nil {
		return nil, false, err
	}
	return cd, has, nil
}

func (card *CardModel) BindBobo(pid int64) error {
	user := &CardBindModel{
		Id:        1,
		PatientId: pid,
	}
	_, err := app.DB().Table("ho_patientcard_item").ID(1).Cols("patient_id").Update(user)
	if err != nil {
		log.Println(err)
		return err
	}
	return nil
}

func (rm *CardModel) Query(req *ReqCardQuery) ([]CardModel, int64, error) {
	cms := make([]CardModel, 0)
	//local, _ := time.LoadLocation("Asia/Shanghai")
	//t := time.Now().In(local).Format("2006-01-02 15:04:05")
	fmt.Println(req.Status != "")
	s := app.DB().Table("ho_patientcard")
	if req.PatientId != "" {
		pid := fmt.Sprintf("%%%s%%", req.PatientId)
		s.Where("source_id like ?", pid)
	}

	total, err := s.Limit(req.Limit, req.Offset).Desc("created_at").FindAndCount(&cms)
	if err != nil {
		return nil, 0, err
	}
	return cms, total, err
}

func (card *CardModel) UpdateNameSourceId(id int64, patientId string, name string) error {
	cd := &CardModel{}
	cd.RealName = name
	cd.SourceId = patientId
	_, err := app.DB().Table("ho_patientcard").ID(id).Cols("source_id", "real_name").Update(cd)
	if err != nil {
		log.Println(err)
		return err
	}
	return nil
}

func (card *CardModel) FindOpenidBySourceId(patientId string) ([]UserModel, error) {
	cd := &CardModel{}
	users := make([]CardBindModel, 0)
	cd.SourceId = patientId
	has, err := app.DB().Table("ho_patientcard").Where("source_id = ?", patientId).Get(cd)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	if !has {
		return nil, fmt.Errorf("登记号错误")
	}
	_, err = app.DB().Table("ho_patientcard_item").Where("patient_id = ? and status = 1", cd.Id).FindAndCount(&users)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	list := make([]UserModel, 0)

	for _, item := range users {
		x := &UserModel{}
		has1, _ := app.DB().Table("wx_userinfo").Where("unionid = ?", item.Unionid).Get(x)
		if has1 {
			list = append(list, *x)
		}
	}

	return list, nil
}
